<template>
	<view class="container">
		<BackIcon />
		<view class="flex j-a-c">
			<sb-img w="160" @click.native='chooseAvatar' r='160' :src="form.avatar" />
		</view>
		<u-gap height="20"></u-gap>
		<u-form-item label="昵称">
			<u-input v-model="form.nickname" border placeholder='请输入昵称' />
		</u-form-item>
		<!-- #ifdef MP-WEIXIN -->
		<u-button :custom-style="{margin:'50rpx auto'}" @click='getUserInfo' shape="circle" type="success">
			使用微信头像和昵称</u-button>
		<!-- #endif -->
		<u-button :custom-style="{margin:'50rpx auto'}" @click='save' shape="circle" type="primary">
			保存设置
		</u-button>
	</view>
</template>

<script>
	import {
		convertObj2Str
	} from 'love-u'
	import {
		BASE_API
	} from '@/config'
	export default {
		data() {
			return {
				form: {
					nickname: "",
					avatar: ""
				},
			}
		},
		created() {
			// 监听从裁剪页发布的事件，获得裁剪结果
			uni.$on('uAvatarCropper', path => {
				this.handleUploadAvatar(path)
			})
		},
		methods: {
			getUserInfo(e) {
				uni.getUserProfile({
					desc: "用于完善会员资料",
					success: ({ userInfo }) => {
						this.form.nickname = userInfo.nickName
						this.form.avatar = userInfo.avatarUrl
						this.save()
					},
					fail(e) {
						this.$msg('获取失败');
					}
				})
			},
			async handleUploadAvatar(path) {
				let { success, data } = await this.$upload({ filePath: path })
				//上传完更新数据库
				if (!success) return this.$msg("头像上传失败")
				this.form.avatar = data.url
			},
			chooseAvatar() {
				this.$go2(this.$makeUrl('/uview-ui/components/u-avatar-cropper/u-avatar-cropper', {
					destWidth: 150,
					rectWidth: 100,
					fileType: 'jpg',
				}))
			},
			async save() {
				if (!this.form.nickname) return this.$msg("请输入昵称")
				if (!this.form.avatar) return this.$msg("请选择头像")
				let { success } = await this.$postF('/user/avatarAndNickname', this.form)
				this.$msg(success ? "更新成功" : "更新失败", () => {
					this.$redirectAfterLogin()
				})
			},
		}
	}
</script>

<style lang="scss" scoped>
	.container {
		padding: 150rpx 80rpx;
	}
</style>
